﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using MySql.Data.MySqlClient;

namespace service_desk_blred.Utils
{
    public abstract class DataBase
    {
        /// <summary>
        /// ConnectionString recuperada do arquivo de configuração de aplicações Web.config
        /// </summary>
        private static readonly string CONN_STRING = ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString;

        /// <summary>
        /// Abrir conexao com banco
        /// </summary>
        public static MySqlConnection createConnection()
        {
            using (MySqlConnection conn = new MySqlConnection(CONN_STRING))
            {
                try
                {
                    return conn;
                }
                catch (Exception ex)
                {
                    conn.Close();
                    conn.Dispose();
                    throw (ex);
                }
            }
        }

        /// <summary>
        /// Fecha conexao com Banco
        /// </summary>
        public static void closeConnection(MySqlConnection conn)
        {
            conn.Close();
            conn.Dispose();
        }

        /// <summary>
        /// Executa nonQuerys
        /// </summary>
        public static int ExecuteNonQuery(MySqlCommand cmd)
        {

            using (MySqlConnection conn = new MySqlConnection(CONN_STRING))
            {
                try
                {
                    conn.Open();
                    cmd.Connection = conn;

                    int rowsAfected = cmd.ExecuteNonQuery();

                    conn.Close();
                    conn.Dispose();

                    return rowsAfected;

                }
                catch (Exception ex)
                {
                    conn.Close();
                    conn.Dispose();
                    throw (ex);
                }
            }
        }

        public static MySqlDataReader ExecuteQueryReader(MySqlCommand cmd)
        {

            using (MySqlConnection conn = new MySqlConnection(CONN_STRING))
            {
                try
                {
                    conn.Open();
                    cmd.Connection = conn;

                    MySqlDataReader dr = cmd.ExecuteReader();

                    conn.Close();
                    conn.Dispose();

                    return dr;


                }
                catch (Exception ex)
                {
                    conn.Close();
                    conn.Dispose();
                    throw (ex);
                }
            }
        }

    }
}